//专门用来存放关于书籍详情的所有接口
const Router = require('koa-router'); //引入路由
const bookdetails = new Router();
const db = require('../utils/db');
//写对应的接口

bookdetails.get('/',async ctx=>{
    let data = await new Promise((reslove,reject) => {
        return db.query(`select * from bookdetails_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
            })
        })
        ctx.body = data;
    })


//插入文章
bookdetails.post('/insert', async ctx => {

    let searchSql0 = `select MAX(id) from bookdetails_class`;
    let idresult = await new Promise((resolve, reject) => {
        return db.query(searchSql0,(err,data)=>{
            if(err) throw err
            resolve(data[0])
        })
    }) 


    const data = ctx.request.body
    console.log(data);
    let searchSql = `insert into bookdetails_class (id,bookname,Content_introduction_title,Content_introduction,Book_introduction_title,Book_introduction,Book_url) values ("${++idresult['MAX(id)']}","${data.bookname}","内容简介","${data.Content_introduction}","书籍记载","${data.Book_introduction}","${data.Book_url}")`
    
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err
            resolve(data)
        })
    })
    let result0 = await new Promise((reslove,reject) => {
        return db.query(`select * from bookdetails_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
        })
    })
    //返回所有数据
    ctx.body = result0;
})



//删除书籍信息    
bookdetails.post('/delete/:id',async ctx=>{
    const {id} = ctx.request.params
    let searchSql = `delete from bookdetails_class where id="${id}"`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err
            resolve(data)
        })
    })
    let result0 = await new Promise((reslove,reject) => {
        return db.query(`select * from bookdetails_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
        })
    })
    //返回所有数据
    ctx.body = result0;
})


module.exports = bookdetails;